package org.agilelang.generator.webservices.php;

/*
 AgileLang - A fourth generation language(http://www.agilelang.org).

 Copyright (C) 2013 Roderick Cusirramos (roderick20@hotmail.com)

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.agilelang.mvc.Generator;
import org.agilelang.mvc.IModel;
import org.agilelang.object.Model;
import org.agilelang.object.Project;
import org.agilelang.object.WebClient;
import org.agilelang.object.WebServices;
import org.agilelang.object.attributes.Attribute;
import org.agilelang.object.attributes.Reference;

public class GWebClient extends Generator implements IModel {

    public GWebClient(String path, Project project) {
        this.path = path;
        this.models = project.models;
        this.webclients = project.webclient;
        this.webservices = project.webservices;
        this.setTemplate2("webservices/php");
        this.template = "bootstrap";
    }

    @Override
    public void process() {
        int t = webclients.size();
        for (int i = 0; i < t; i++) {

            String list_view_th = "";
            String list_view_form = "";
            String list_view_search = "";
            String list_js_clear = "";
            String list_js_td = "";
            String list_js_td_blank = "";
            String list_js_param = "";
            String list_js_save = "";
            String list_js_find = "";
            String list_js_rules = "";
            String list_js_messages = "";
            String list_js_find_function = "";
            String list_js_find_keypress = "";
            String list_ws_view = "";

            String list_references_load = "";

            WebClient webclient = webclients.get(i);
            WebServices webservice = getWebServicesByName(webclient.webservice);
            Model model = this.getModelByName(webservice.model);
            List<Attribute> listattr = model.attributes;
            Collections.sort(listattr, new CustomComparator());
            int ta = listattr.size();
            for (int j = 0; j < ta; j++) {
                Attribute attr = listattr.get(j);
                Reference ref2 = this.isKey(model.name, attr.name);


                if (ref2 == null) {
                    list_view_form += "<div class=\"control-group\">\n"
                            + "\t<label class=\"control-label\" for=\"form_" + attr.name + "\">" + attr.caption + "</label>\n"
                            + "\t<div class=\"controls\">\n"
                            + "\t\t<input type=\"text\" id=\"form_" + attr.name + "\" name=\"form_" + attr.name + "\" placeholder=\"" + attr.caption + "\" value=\"\">\n"
                            + "\t</div>\n"
                            + "</div>\n";
                } else {
                    list_view_form += "<div class=\"control-group\">\n"
                            + "\t<label class=\"control-label\" for=\"form_" + attr.name + "\">" + attr.caption + "</label>\n"
                            + "\t<div class=\"controls\">\n"
                            + "\t\t<select id=\"form_" + attr.name + "\" name=\"form_" + attr.name + "\" placeholder=\"" + attr.caption + "\"></select>\n"
                            + "\t</div>\n"
                            + "</div>\n";

                    list_references_load += "\t$.getJSON(\"webservices/" + model.name.toLowerCase() + "_ws.php?f=get_list_" + ref2.model_reference.toLowerCase() + "\", {},\n"
                            + "\t\tfunction(data) {\n"
                            + "\t\t\t$.each(data.result, function(i, item) {\n"
                            + "\t\t\t\t$(\"#form_" + ref2.foreign_key + "\").append(\"<option value=\\\"\"+item." + ref2.model_reference.toLowerCase() + ".id+\"\\\" >\"+item." + ref2.model_reference.toLowerCase() + "." + ref2.field_reference + "+\"</option>\");	\n"
                            + "\t\t\t});\n"
                            + "\t});\n";
                }
                if (!attr.validate.equals("")) {
                    list_js_rules += "\t\t\tform_" + attr.name + ": {" + attr.validate.replace("-", ",") + "},\n";
                    if (attr.message_error.equals("")) {
                        list_js_messages += "\t\t\tform_" + attr.name + ": 'Error',\n";
                    } else {
                        list_js_messages += "\t\t\tform_" + attr.name + ": '" + attr.message_error + "',\n";
                    }

                }



                list_js_clear += "\t\t$(\"#form_" + attr.name + "\").val(\"\");\n";
                list_js_param += "\""+attr.name +"\""+ " : " + attr.name + ", ";
                list_js_save += attr.name + " = $(\"#form_" + attr.name + "\").val();\n";
                list_ws_view += "$(\"#form_" + attr.name + "\").val(data." /*+ this.setPluralize(model.name).toLowerCase() + "." */+ attr.name + ");\n";
                if (attr.field.equals("true")) {
                    list_view_th += "<th>" + attr.caption + "</th>";
                    list_view_search += "<td>\n"
                            + "<div class=\"input-append\"  style=\"margin-bottom: 0px;\">\n"
                            + "<input class=\"span2\" id=\"search_txt_" + attr.name + "\" type=\"text\" onkeypress=\"return keypress_" + attr.name + "(event)\" >\n"
                            + "<span id=\"search_" + attr.name + "\" class=\"add-on\" style=\"cursor:pointer;\"><i class=\"icon-search\"></i></span>\n"
                            + "</div>\n"
                            + "</td>\n";

                    Reference ref = this.isKey(model.name, attr.name);
                    if (ref == null) {
                        list_js_td += "<td>\" + item." + this.setPluralize(model.name).toLowerCase() + "." + attr.name + " + \"</td>";
                    } else {
                        list_js_td += "<td>\" + item." + this.setPluralize(ref.model_reference).toLowerCase() + "." + ref.field_reference + " + \"</td>";
                    }

                    list_js_td_blank += "<td>&nbsp;</td>";

                    list_js_find += "\t$(\"#search_" + attr.name + "\").click(function() {\n"
                            + "\t\tfind_by_" + attr.name + "(0, 13, $(\"#search_txt_" + attr.name + "\").val())\n"
                            + "\t});\n";

                }
            }

            for (int j = 0; j < ta; j++) {
                Attribute attr = listattr.get(j);
                if (attr.field.equals("true")) {
                    String file = readStreamTpl("_find_script");
                    file = file.replace("//name//", attr.name);
                    file = file.replace("//nameclass//", model.name.toLowerCase());
                    file = file.replace("//table//", this.setPluralize(model.name).toLowerCase());
                    file = file.replace("//list_js_clear//", list_js_clear);
                    file = file.replace("//list_js_td//", list_js_td + "\"");
                    file = file.replace("//list_js_td_blank//", list_js_td_blank);
                    list_js_find_function += file;

                    list_js_find_keypress += "function keypress_" + attr.name + "(e) {\n"
                            + "\tif (e.keyCode == 13) {\n"
                            + "\t\tfind_by_" + attr.name + "(0, 13, $(\"#search_txt_" + attr.name + "\").val())\n"
                            + "\t\treturn false;\n"
                            + "\t}\n"
                            + "}\n";
                }
            }

            String file = readStreamTpl("m_view.php.tpl");
            file = file.replace("//NAMECLASS//", model.caption);
            file = file.replace("//nameclass//", model.name.toLowerCase());
            file = file.replace("//list_view_th//", list_view_th);
            file = file.replace("//list_view_form//", list_view_form);
            file = file.replace("//list_view_search//", list_view_search);
            createfile("/client/views/" + model.name.toLowerCase() + ".php", path, file);

            file = readStreamTpl("m_script_old");
            file = file.replace("//nameclass//", model.name.toLowerCase());
            file = file.replace("//table//", this.setPluralize(model.name).toLowerCase());
            file = file.replace("//list_js_clear//", list_js_clear);
            file = file.replace("//list_js_td//", list_js_td + "\"");
            file = file.replace("//list_js_td_blank//", list_js_td_blank);
            file = file.replace("//list_js_param//", list_js_param.substring(0, list_js_param.length() - 2));
            file = file.replace("//list_js_save//", list_js_save);
            file = file.replace("//list_ws_view//", list_ws_view);
            file = file.replace("//list_js_find//", list_js_find);
            file = file.replace("//list_js_find_function//", list_js_find_function);
            file = file.replace("//list_js_find_keypress//", list_js_find_keypress);
            file = file.replace("//list_references_load//", list_references_load);
            file = file.replace("//list_js_rules//", list_js_rules);
            file = file.replace("//list_js_messages//", list_js_messages);

            createfile("/client/scripts/" + model.name.toLowerCase() + ".js", path, file);
        }
    }

    public class CustomComparator implements Comparator<Attribute> {

        @Override
        public int compare(Attribute o1, Attribute o2) {
            return Integer.parseInt(o1.item) - Integer.parseInt(o2.item);
        }
    }
}
